import request from '@/uni_modules/dx-admin/libs/request';
import { throttle } from '@/uni_modules/dx-admin/libs/utils';
import { userInfoStore } from '@/uni_modules/dx-admin/stores/user';
let apiFlag = false;
//请求拦截
request.interceptor.request(function (param: any) {
	// 无感刷新token
	const userStore = userInfoStore();
	if (!apiFlag && userStore.isLogin && userStore.checkLogin()) {
		apiFlag = true;
		request
			.send('user/getUserInfo', 'dx-func-user')
			.then((res: any) => {
				if (res.code === 1000) {
					userStore.setUserInfo(res.data);
				}
			})
			.finally(() => {
				apiFlag = false;
			});
	}
	return param;
});

//响应拦截，判断状态码是否通过
request.interceptor.response(function (res: any) {
	if (res.code === 4001) {
		throttle(() => {
			ElMessage.error(res.message);
			setTimeout(() => {
				uni.reLaunch({
					url: '/uni_modules/dx-admin/pages/login/login',
					complete(e) {
						console.log('reLaunch', e);
					},
				});
			}, 1000);
		}, 3000);
		return false;
	}
	return res;
});
// 导出 request
export const axios = request;
// 获取验证码
export const getCaptcha = (params = {}) => request.send('index/getCaptcha', 'dx-func-user', params);
// 登陆
export const login = (params = {}) => request.send('index/login', 'dx-func-user', params);
// 获取用户信息
export const getUserInfo = (params = {}) => request.send('user/getUserInfo', 'dx-func-user', params);
// 编辑用户信息
export const editUserInfo = (params = {}) => request.send('user/edit', 'dx-func-user', params);
// 应用信息
export const indexInit = (params = {}) => request.send('index/index', 'dx-func-admin', params);
// 菜单
export const getMenuList = (params = {}) => request.send('menu/list', 'dx-func-admin', params);
// 权限生成
export const createPermission = (params = {}) => request.send('permission/createPermission', 'dx-func-admin', params);
// 配置列表
export const configList = (params = {}) => request.send('config/list', 'dx-func-admin', params);
// 保存配置
export const configSave = (params = {}) => request.send('config/save', 'dx-func-admin', params);
// 获取app列表
export const getAppList = (params = {}) => request.send('app/list', 'dx-func-admin', params);
// 单文件上传请求
export const upload = ({ name, size, path, type }: any, query = {}, index?: number) => {
	return new Promise(async (resolve, reject) => {
		let y, m, d, day, rand, cloudPath;
		d = new Date();
		y = d.getFullYear().toString();
		m = (d.getMonth() + 1).toString().padStart(2, '0');
		day = d.getDate().toString().padStart(2, '0');
		rand = (index || 0).toString().padStart(4, '0');
		cloudPath = y + '/' + m + '/' + day + '/' + Date.now() + rand + '.' + name.split('.').pop();
		const result = await uniCloud.uploadFile({
			cloudPathAsRealPath: true,
			filePath: path,
			cloudPath,
			onUploadProgress(e) {
				console.log(e);
			},
		});
		console.log('上传结果：', result);
		let url = '';
		if (/^cloud:\/\//.test(result.fileID)) {
			//腾讯云处理
			const { fileList } = await uniCloud.getTempFileURL({
				fileList: [result.fileID],
			});
			if (fileList.length) {
				url = fileList[0].tempFileURL || fileList[0].download_url;
			}
		} else {
			url = result.fileID;
		}
		if(type && type.length > 15) {
			type = name.split('.').pop();
		}
		//上传云储存成功处理【保存数据库】
		if (url) {
			request
				.send('resource/add', 'dx-func-admin', {
					file_id: result.fileID,
					url,
					file_size: size,
					file_name: name,
					type: type,
					...query,
				})
				.then((res) => {
					if (res.code === 1000) {
						console.log('保存成功', res);
						resolve(index === void 0 ? url : { url, index });
					} else {
						reject(res.message);
					}
				});
		} else {
			reject();
		}
	});
};
// 多文件上传
export const multiUpload = (files: any[], query = {}, max = 6) => {
	return new Promise(async (resolve) => {
		let pool: any = []; //并发池
		let result: any = [];
		for (let i = 0; i < files.length; i++) {
			let url = files[i];
			let task = upload(url, query, i);
			task.then((data) => {
				//每当并发池跑完一个任务,从并发池删除个任务
				pool.splice(pool.indexOf(task), 1);
				result.push(data);
				if (pool.length === 0) {
					resolve(result.sort((a: any, b: any) => a.index - b.index).map((item: any) => item.url));
				}
			});
			pool.push(task);
			if (pool.length === max) {
				await Promise.race(pool);
			}
		}
	});
};
